package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.FlowerVo;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import javafx.scene.shape.Circle;
import org.bson.types.ObjectId;

import com.tanhua.commons.template.HuanXinTemplate;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.mongo.UserLike;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service(timeout = 500000)
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private FriendApi friendApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;


    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        // 1.查询今日佳人, 构造查询条件
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(1)
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        query.limit(1);

        // 2. 查询
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        return recommendUser;
    }

    @Override
    public PageResult queryRecommendation(Long userId, Integer page, Integer pagesize) {
        //1. 查询首页推荐，构造查询条件
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(5).skip(0)
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(5).skip(5)
        //db.recommend_user.find({userId:20}).sort({score:-1}).limit(5).skip(10)
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("score")));
        query.limit(pagesize).skip((page - 1) * pagesize);
        //2. 分页查询: 当前页数据
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //3. 统计
        long count = mongoTemplate.count(query, RecommendUser.class);
        //4. 创建分页对象并返回
        return new PageResult(page, pagesize, (int) count, recommendUserList);
    }

    @Autowired
    private UserInfoApi userInfoApi;
    @Override
    public List<FlowerVo> queryRecommendation(Long userId) {
        //查询所有的探花用户
        Query query = new Query(Criteria.where("userId").is(userId));
        List<RecommendUser> recommendUsers = mongoTemplate.find(query, RecommendUser.class);

        //创建一个集合返回探花用户
        List<FlowerVo> voList = new ArrayList<>();
        //筛选已经喜欢过的用户和已经是好友的用户
        if (recommendUsers != null && recommendUsers.size() > 0) {
            for (RecommendUser recommendUser : recommendUsers) {
                Long recommendUserId = recommendUser.getRecommendUserId();
                if (queryFriend(userId,recommendUserId))continue;
                if (queryByFans(userId,recommendUserId))continue;
                FlowerVo vo = new FlowerVo();
                UserInfo userInfo = userInfoApi.findById(recommendUserId);
                if (userInfo!=null){
                    BeanUtils.copyProperties(userInfo,vo);
                    vo.setId(userInfo.getId().intValue());
                    if (userInfo.getTags()!=null){
                        vo.setTags(userInfo.getTags().split(","));
                    }
                }
                voList.add(vo);
            }
        } else {
            FlowerVo vo = new FlowerVo();
            vo.setId(50);
            vo.setAvatar(userInfoApi.findById(userId).getAvatar());
            vo.setNickname("你好我好");
            vo.setGender("女");
            vo.setAge(18);
            vo.setTags(userInfoApi.findById(userId).getTags().split(","));
        voList.add(vo);
        }
        return voList;
    }

    private Boolean queryFriend(Long userId, Long recommendUserId) {

        Query friend = new Query(Criteria.where("userId").is(userId)
                .and("friendId").is(recommendUserId));
        return mongoTemplate.exists(friend, Friend.class);

    }
    private Boolean queryByFans(Long userId, Long recommendUserId) {

        Query like = new Query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(recommendUserId));
        return mongoTemplate.exists(like, UserLike.class);
    }

    @Override
    public Long queryScore(Long userId, Long recommendUserId) {
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("recommendUserId").is(recommendUserId)).limit(1);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);
        if (recommendUser == null) {
            return 70L;
        }
        return recommendUser.getScore().longValue();
    }



    @Override
    public void disLike(Long userId, Long id) {
        //通过传进来的id查询喜欢列表有没有，如果有就删除，如果没有就不执行;
        Query query = new Query(Criteria.where("userId").is(userId)
                .and("likeUserId").is(id)
        );
        //查询有
        if (mongoTemplate.exists(query, UserLike.class)) {
            //执行删除
            mongoTemplate.remove(query, UserLike.class);
        } else {
            //喜欢列表没有则不执行
            return;
        }
    }


    @Override
    public void loveFlower(Long userId, Long id) {
        //2.根据探花用户id，查询喜欢列表对方有没有喜欢过在线用户，
        Query query = new Query(Criteria.where("userId").is(id)
                .and("likeUserId").is(userId)
        );
        //3.如果有探花用户id有喜欢过，则在好友表里面插入两条数据，删除掉喜欢列表的数据跟粉丝列表里面的数据，通过环信加入到好友id里面
        if (mongoTemplate.exists(query, UserLike.class)) {
            //添加到好友列表
            friendApi.save(userId, id);
            //删除掉喜欢列表里面的用户数据
            mongoTemplate.remove(query, UserLike.class);
            huanXinTemplate.contactUsers(userId, id);
        } else {
            //4.如果没有就在喜欢列表添加一条数据，再往探花用户ID粉丝列表添加一条数据
            UserLike userLike = new UserLike();
            userLike.setId(new ObjectId());
            userLike.setUserId(userId);
            userLike.setLikeUserId(id);
            userLike.setCreated(System.currentTimeMillis());
            mongoTemplate.insert(userLike);
        }
    }
}
